import re
from django.http import Http404
from django.shortcuts import render, get_object_or_404

from comments.forms import CommentForm
from gustbook.forms import GustBookForm
from gustbook.models import GustBook
from myblog.models import Article


# Create your views here.


def index(request):
    try:
        article_list = Article.objects.all().order_by('-pub_date')
    except Exception as e:
        raise Http404
    article_image_list = []
    for article in article_list:
        content = article.content
        # <p>测试文件<img src="/media/uploads/blog/images/123_20180730101259_199.png" alt="123.png"/></p>
        try:
            ret = re.search(r'<img src="(.*?)" alt=".*"/>', content)
            if ret:
                article_image_list.append((article, ret.group(1)))
            else:
                article_image_list.append((article, None))
        except Exception as e:
            print(e)
    return render(request, 'blog/index.html', {'article_image_list': article_image_list})


def detail(request, cid):
    article = get_object_or_404(Article, id=cid)
    form = CommentForm()
    try:
        comment_list = article.comment_set.all()
    except Exception as e:
        raise Http404
    context = {
        "article": article,
        "comment_list": comment_list,
        "form": form
    }
    return render(request, 'blog/detail.html', context=context)


def gustbook(request):
    try:
        gustbook_list = GustBook.objects.all()
    except Exception as e:
        raise Http404
    form = GustBookForm()
    context = {
        "form": form,
        "gustbook_list": gustbook_list
    }
    return render(request, 'blog/gustbook.html', context)


def category(request):
    try:
        article_list = Article.objects.all()
    except Exception as e:
        raise Http404
    category_list = []
    for article in article_list:
        category_str = article.category
        article_count = Article.objects.filter(category=category_str).count()
        if (category_str, article_count) not in category_list:
            category_list.append((category_str, article_count))
    context = {
        "category_list": category_list
    }
    return render(request, 'blog/category.html', context=context)
